package day3.HomeWork;

/**
 * ClassName：Test12
 *
 * @Author：小鱼
 * @Create：2025-08-21 10:30
 */
public class Test12 {
    // 创建两个共享资源（锁对象）
    private static final Object LOCK_A = new Object();
    private static final Object LOCK_B = new Object();

    public static void main(String[] args) {
        // 线程1：先获取LOCK_A，再尝试获取LOCK_B
        Thread thread1 = new Thread() {
            @Override
            public void run() {
                synchronized (LOCK_A) {
                    System.out.println("线程1已获取LOCK_A，等待LOCK_B...");
                    try {
                        // 休眠1秒，确保线程2有时间获取LOCK_B
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    // 尝试获取LOCK_B（此时已被线程2持有）
                    synchronized (LOCK_B) {
                        System.out.println("线程1已获取LOCK_B，执行完成");
                    }
                }
            }
        };

        // 线程2：先获取LOCK_B，再尝试获取LOCK_A
        Thread thread2 = new Thread() {
            @Override
            public void run() {
                synchronized (LOCK_B) {
                    System.out.println("线程2已获取LOCK_B，等待LOCK_A...");
                    try {
                        // 休眠1秒，确保线程1有时间获取LOCK_A
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    // 尝试获取LOCK_A（此时已被线程1持有）
                    synchronized (LOCK_A) {
                        System.out.println("线程2已获取LOCK_A，执行完成");
                    }
                }
            }
        };

        // 启动线程
        thread1.start();
        thread2.start();
    }
}
